package com.android.baselibrary.base

import android.os.Bundle
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.launcher.ARouter
import com.android.baselibrary.utils.getViewModelOfActivity
import java.lang.reflect.ParameterizedType

/**
 * @author: Mr.You
 * @create: 2023-11-24 17:08
 * @description:
 **/
abstract class BaseVMActivity<DB : ViewDataBinding, VM : ViewModel>(@LayoutRes val layoutId: Int = 0) :
    AppCompatActivity() {
    private lateinit var mBinding: DB
    private var mLayoutId = layoutId
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (layoutId == 0) {
            mLayoutId = getActivityLayoutId()
        }

        mBinding = DataBindingUtil.setContentView(this, mLayoutId)
        val viewModel = getViewModel()
        val variableId = getVariableId()
        if (variableId != -1 && viewModel != null) {
            mBinding.setVariable(variableId, viewModel)
            mBinding.executePendingBindings()
        }
        ARouter.getInstance().inject(this)
        initView()
        initVMData()
    }

    abstract fun initView()

    abstract fun initVMData()


    private fun getViewModel(): VM? {
        //这里获得到的是类的泛型的类型
        val type = javaClass.genericSuperclass
        if (type != null && type is ParameterizedType) {
            val actualTypeArguments = type.actualTypeArguments
            val tClass = actualTypeArguments[1]
            return ViewModelProvider(
                this,
                ViewModelProvider.AndroidViewModelFactory.getInstance(application)
            )
                .get(tClass as Class<VM>)
        }
        return null
    }

    open fun getActivityLayoutId():Int {
        return 0
    }

    abstract fun getVariableId(): Int
}